﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Text;

using Model = RBS.Core.Model;
using Bll = RBS.Core.BLL;
using RBS.Core.Extension;

using RBS.Core.Model;

using UIModel = RBS.Web.Hotel.Models;

namespace RBS.Web.Hotel.Service
{
    public class DineService
    {

        #region Private Fields

        private Bll.D_Order _order_bll;
        private Bll.D_Order_Details _orderDetail_bll;
        private Bll.D_OperateRecord _operateRecord_bll;
        private Bll.D_CuiCai _cuiCai_bll;

        #endregion

        #region Ctors

        public DineService() {
            _order_bll = new Bll.D_Order();
            _orderDetail_bll = new Bll.D_Order_Details();
            _operateRecord_bll = new Bll.D_OperateRecord();
            _cuiCai_bll = new Bll.D_CuiCai();
        }

        #endregion

        #region 修改订单

        #endregion

        #region 确认|取消|结算订单

        /// <summary>
        /// 确认订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public Boolean ConfirmOrder(Int32 orderId) {
            Boolean result = false;

            var model = _order_bll.GetModel(orderId);
            if (model.OrderState == 0)
            {
                model.OrderState = 1;
                _order_bll.Update(model);
                result = true;
            }
            else {
                throw new Exception(String.Format("当前订单状态无法再确认！OrderState:{0}", model.OrderState));
            }

            return result;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public Boolean CancelOrder(Int32 orderId) {
            Boolean result = false;

            var model = _order_bll.GetModel(orderId);
            if (model.OrderState == 0 || model.OrderState == 1 || model.OrderState == 2 || model.OrderState == 4)
            {
                model.OrderState = 3;
                _order_bll.Update(model);
                result = true;
            }
            else
            {
                throw new Exception(String.Format("当前订单状态无法再取消！OrderState:{0}", model.OrderState));
            } 
            return result;
        }

        /// <summary>
        /// 订单结算
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public Boolean CheckOutOrder(Int32 orderId) {
            Boolean result = false;

            var model = _order_bll.GetModel(orderId);
            if (model.OrderState != -1 || model.OrderState != 3)
            {
                model.OrderState = 4;
                _order_bll.Update(model);
                result = true;
            }
            else
            {
                throw new Exception(String.Format("当前订单状态无法再结算！OrderState:{0}", model.OrderState));
            }

            return result;
        }
        /// <summary>
        /// 就坐
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public Boolean CheckinOrder(Int32 orderId)
        {
            Boolean result = false;

            var model = _order_bll.GetModel(orderId);
            if (model.OrderState != -1 || model.OrderState != 3)
            {
                model.OrderState = 4;
                _order_bll.Update(model);
                result = true;
            }
            else
            {
                throw new Exception(String.Format("当前订单状态无法再结算！OrderState:{0}", model.OrderState));
            }

            return result;
        }


        

        #endregion

        #region 订单查询

        /// <summary>
        /// 查询订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public UIModel.Dine.OrderViewModel GetOrder(Int32 orderId, Boolean isLoadOrderDetail)
        {
            UIModel.Dine.OrderViewModel orderModel = null;

            Model.D_Order orderEntity = _order_bll.GetModel(orderId);
            if (orderEntity == null)
                throw new Exception(String.Format("无效的订单ID:{0}", orderId));

            orderModel = new UIModel.Dine.OrderViewModel()
            {
                #region 基本信息赋值

                OrderID = orderEntity.Id,
                OrderState = (UIModel.Dine.OrderState)orderEntity.OrderState, //row["OrderState"].ToEnum<UIModel.Dine.OrderState>(),
                OrderChannel = orderEntity.OrderChannel.ToEnum<UIModel.Dine.OrderChannel>(), //row["OrderChannel"].ToEnum<UIModel.Dine.OrderChannel>(),
                ContactUser = orderEntity.ContactUser, //row["ContactUser"].ToString(),
                ContactMobile = orderEntity.ContactMobile, //row["ContactMobile"].ToString(),
                OrderRemark = orderEntity.OrderRemark, //row["OrderRemark"].ToString(),
                OrderAmount = orderEntity.OrderAmount, //row["OrderAmount"].ToDecimal(),
                RecAmount = orderEntity.RecAmount, //row["RecAmount"].ToDecimal(),
                DisAmount = orderEntity.DisAmount, //row["DisAmount"].ToDecimal(),
                AccAmount = orderEntity.AccAmount, //row["AccAmount"].ToDecimal(),
                PayType = orderEntity.PayType.ToEnum<UIModel.Dine.PayType>(),//row["PayType"].ToEnum<UIModel.Dine.PayType>(),
                ReserveDate = orderEntity.ReserveDate, //row["ReserveDate"].ToString(),
                ReserveTime = orderEntity.ReserveTime, //row["ReserveTime"].ToString(),
                DineNum = orderEntity.DineNum, //row["DineNum"].ToInt32(),
                CreateTime = orderEntity.CreateTime, //row["CreateTime"].ToDateTime(),
                CreateUser = orderEntity.CreateUser, //row["CreateUser"].ToString(),
                LastModifyDate = orderEntity.LastModifyDate, //row["LastModifyDate"].ToDateTime(),
                LastModifyUser = orderEntity.LastModifyUser, //row["LastModifyUser"].ToString()
                 OrderTime = orderEntity.OrderTime,
                DineTable = new RBS.Core.BLL.Hotel.H_Hotel_Seat().GetModelByCache(orderEntity.DineTable).Name
                
                #endregion
            };
            if (isLoadOrderDetail)
            {
                #region 加载订单详细

                var orderDetail_list = new RBS.Core.BLL.V_OrderDetails().GetModelList(String.Format(" OrderId='{0}' ", orderId));

                if (orderDetail_list != null && orderDetail_list.Any())
                {
                    orderModel.OrderDetails = new List<UIModel.Dine.OrderDetailViewModel>();
                    orderDetail_list.ForEach(entity => orderModel.OrderDetails.Add(new UIModel.Dine.OrderDetailViewModel 
                        {
                            Id = entity.Id,
                            OrderId = entity.OrderId,
                            HCId = entity.HCId,
                            CName = entity.CName,
                            Num = entity.Num,
                            Price = entity.Price,
                            DisAmount = entity.DisAmount, 
                            State = entity.State  
                        
                        }));
                }

                #endregion
            }
            return orderModel;
        }

        /// <summary>
        /// 查询订单列表
        /// </summary>
        /// <returns></returns>
        public IList<UIModel.Dine.OrderViewModel> QueryOrderList(UIModel.Dine.OrderQueryCondition condition, out Int32 recordCount)
        {
            IList<UIModel.Dine.OrderViewModel> list = new List<UIModel.Dine.OrderViewModel>();

            recordCount = 0;
            DataSet orderDS = _order_bll.GetList(condition.PageSize, condition.PageIndex, condition.ConvertToSql(), condition.OrderField, out recordCount);
            if (orderDS != null && orderDS.Tables.Count > 0) {
                foreach (DataRow row in orderDS.Tables[0].Rows) {
                    var orderId = row["Id"].ToInt32();

                    var model = new UIModel.Dine.OrderViewModel()
                    {
                        #region 基本信息赋值

                        OrderID = row["Id"].ToInt32(),
                        OrderState = row["OrderState"].ToEnum<UIModel.Dine.OrderState>(),
                        OrderChannel = row["OrderChannel"].ToEnum<UIModel.Dine.OrderChannel>(),
                        ContactUser = row["ContactUser"].ToString(),
                        ContactMobile = row["ContactMobile"].ToString(),
                        OrderRemark = row["OrderRemark"].ToString(),
                        OrderAmount = row["OrderAmount"].ToDecimal(),
                        RecAmount = row["RecAmount"].ToDecimal(),
                        DisAmount = row["DisAmount"].ToDecimal(),
                        AccAmount = row["AccAmount"].ToDecimal(),
                        PayType = row["PayType"].ToEnum<UIModel.Dine.PayType>(),
                        ReserveDate = row["ReserveDate"].ToString(),
                        ReserveTime = row["ReserveTime"].ToString(),
                        DineNum = row["DineNum"].ToInt32(),
                        CreateTime = row["CreateTime"].ToDateTime(),
                        CreateUser = row["CreateUser"].ToString(),
                        LastModifyDate = row["LastModifyDate"].ToDateTime(),
                        LastModifyUser = row["LastModifyUser"].ToString(),
                        DineTable = new Bll.Hotel.H_Hotel_Seat().GetModelByCache(Convert.ToInt32(row["DineTable"])).Name,
                        OrderTime = row["OrderTime"].ToDateTime()

                        #endregion
                    };

                    #region 订单详细商品信息

                    DataSet detailDS = _orderDetail_bll.GetList(String.Format(" OrderId ='{0}' ", orderId));
                    if (detailDS != null && detailDS.Tables.Count > 0) {
                        model.OrderDetails = new List<UIModel.Dine.OrderDetailViewModel>();
                        foreach (DataRow row2 in detailDS.Tables[0].Rows) {
                            var orderDetail = new UIModel.Dine.OrderDetailViewModel()
                            {
                                Id = row2["Id"].ToInt32(),
                                OrderId = orderId,
                                HCId = row2["HCId"].ToInt32(),
                                CName = row2["CName"].ToString(),
                                Num = row2["Num"].ToInt32(),
                                Price = row2["Price"].ToDecimal(),
                                DisAmount = row2["DisAmount"].ToDecimal(),
                                IsGuest = row2["IsGuest"].ToInt32(),
                                UId = row2["UId"].ToInt32(),
                                State = row2["State"].ToInt32()
                            };
                            model.OrderDetails.Add(orderDetail);
                        }
                    }

                    #endregion

                    list.Add(model);
                }
            }

            return list;
        }

        #endregion

        #region 查询订单操作记录

        public IList<UIModel.Dine.OperateRecordViewModel> QueryOrderOpeateRecord(Int32 orderId)
        {
            return queryOrderOperateRecord(String.Format(" OrderId='{0}'", orderId));
        }

        public IList<UIModel.Dine.OperateRecordViewModel> QueryOrderProductOpeateRecord(Int32 orderId,Int32 orderProductId)
        {
            return queryOrderOperateRecord(String.Format(" OrderId='{0}' and OrderProductId = '{1}' ", orderId, orderProductId));
        }

        private IList<UIModel.Dine.OperateRecordViewModel> queryOrderOperateRecord(String strWhere) {
            IList<UIModel.Dine.OperateRecordViewModel> modelList = null;

            var list = _operateRecord_bll.GetModelList(strWhere);
            if (list != null && list.Any())
            {
                modelList = new List<UIModel.Dine.OperateRecordViewModel>();
                list.ForEach(entity => modelList.Add(new UIModel.Dine.OperateRecordViewModel()
                    {
                        Id = entity.Id,
                        OrderId = entity.OrderID,
                        OrderProductId = entity.OrderProductId,
                        OperateType = entity.OperateType,
                        OperateDesc = entity.OperateDesc,
                        OperateUserId = entity.OperateUserId,
                        OperateUser = entity.OperateUser,
                        OperateDate = entity.OperateDate,
                    }));
            }

            return modelList;
        }

        #endregion

        #region 查询烹饪列表

        /// <summary>
        /// 查询烹饪列表
        /// </summary>
        /// <returns></returns>
        public IList<UIModel.Dine.CookDishViewModel> QueryCookDishList() {
            IList<UIModel.Dine.CookDishViewModel> modelList = null;

            String strWhere = String.Format(" DishState != 2 ");
            List<D_CuiCai> list = _cuiCai_bll.GetModelList(strWhere);
            if (list != null && list.Any()) {
                modelList = new List<UIModel.Dine.CookDishViewModel>();
                list.ForEach(entity =>
                {
                    modelList.Add(new UIModel.Dine.CookDishViewModel(entity));
                });
            }
            return modelList;
        }


        #endregion

        #region 催菜

        /// <summary>
        /// 催菜加速
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Boolean SpeedOrderDish(Int32 id) {
            Boolean result = false;

            var model = _cuiCai_bll.GetModel(id);
            if (model != null) {
                model.PressWeight += 10;
                result = _cuiCai_bll.Update(model);
            }            

            return result;
        }

        #endregion


        public List<UComment> QueryOrderComment(int id)
        {
          return new RBS.Core.BLL.U_Comment().GetModelList("column_10=" + id);
        }
    }
}